package com.zhkj.crawl.rank;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
public class AliexpressService extends BaseService{

    public static void main(String[] args) {
        String itemId = "4001104117628";
        ProductDetail detail = new ProductDetail(itemId);

        getDetail(detail);
        searchByKeyword(detail);

        log.info("查找结束：'{}'的排名是<{}>", detail.getItemId(), detail.getRank());
    }

    private static void searchByKeyword(ProductDetail detail) {
        // 一页60条 取前1000名
        int LIMIT_RANK = 1000,
                PS = 12 * 5,
                limit = (LIMIT_RANK % PS > 0) ? LIMIT_RANK /PS + 1 : LIMIT_RANK / PS,
                page = 0,
                currentIdx = 0;

        log.info("取前{}名 约在第{}页停止", LIMIT_RANK, limit);
        while (currentIdx < LIMIT_RANK){
            ++page;
            JSONObject json = getPage(detail.getCateUrl(), page, 0);
            if(json == null){
                log.info("第{}页 查找出错 - {}", page, "");
                continue;
            }

            JSONArray arr = json.getJSONObject("mods").getJSONObject("itemList").getJSONArray("content");
            List<String> productId = arr.stream().map(s -> ((JSONObject) s).get("productId").toString()).collect(Collectors.toList());

            log.info("查找: {}", productId);
            int idx = productId.indexOf(detail.getItemId());

            if(idx > -1){
                int rank = currentIdx + idx;
                detail.setRank(rank + "");
                log.info("第{}页找到了 排名: {}", page, detail.getRank());
                return;
            }
            log.info("-----------第{}页{}条中未找到-----------", page, productId.size());
            currentIdx += productId.size();
        }
        detail.setRank(String.format("大于前%s名", currentIdx));
    }

    private static void getDetail(ProductDetail detail){
        String url = String.format("https://www.aliexpress.com/item/%s.html", detail.getItemId());
        Document document = jsoupGet(url, 0);

        JSONObject pageJson = getPageJson(document, "data: ");
        String title = pageJson.getJSONObject("titleModule").getString("subject");
        String href = document.select(".breadcrumb").first().select("a").last().attr("href");
        String cateUrl = "https:" + href;

        detail.setKeyword(title);
        detail.setCateUrl(cateUrl);

        log.info("{} 的详情：{}", detail.getItemId(), JSON.toJSONString(detail));
    }

    private static JSONObject getPageJson(Document document, String keyword){
        Optional<Element> scriptEle = document.select("script").stream().filter(s -> s.data().contains("window.runParams")).findFirst();
        if(!scriptEle.isPresent()){
            return null;
        }

        Element element = scriptEle.get();
        String data = element.data();
        for (String s : data.split("\n")) {
            if(s.contains(keyword)){
                s = s.substring(s.indexOf(keyword) + keyword.length());
                s = s.substring(0, s.length() - 1);
                if(s.length() <= 5){ continue; }
                return JSON.parseObject(s);
            }
        }
        return null;
    }

    public static JSONObject getPage(String cateUrl, int page, Integer deep){
        String url = String.format("%s?page=%s", cateUrl, page);

        Document document = jsoupGet(url, deep);
        JSONObject pageJson = getPageJson(document, "window.runParams = ");
        if(++deep <= MAX_RETRY && (pageJson == null || !pageJson.getBoolean("success"))){
            System.out.printf("wait and retry %s(%s)\n", deep, (pageJson == null ? "null" : "false"));
//                showIp();
            sleep(1);
            return getPage(cateUrl, page, deep);
        }
        return pageJson;
    }

}
